/*
 * Copyright 2013 Sigurd Randoll.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.client.infrastructure.rest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import de.digiway.rapidbreeze.client.model.collector.UrlInformationResourceService;
import de.digiway.rapidbreeze.shared.rest.ResourceLocation;
import de.digiway.rapidbreeze.shared.rest.url.UrlResource;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

/**
 *
 * @author Sigurd
 */
public class UrlInformationResourceServiceRestClient implements UrlInformationResourceService {

    private Client client;
    private String host;
    private String username;
    private String password;
    private int port;

    public UrlInformationResourceServiceRestClient(String host, int port, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
        this.client = Client.create();
    }

    @Override
    public UrlResource getUrlResource(URL url) {
        try {
            URI uri = getUri(ResourceLocation.URL_INFORMATION_RESOURCE_PATH, URLEncoder.encode(url.toString()));
            ClientResponse response = client.resource(uri).type(MediaType.APPLICATION_XML).get(ClientResponse.class);
            if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) {
                throw new IllegalStateException("Cannot request " + UrlResource.class.getSimpleName());
            }
            return response.getEntity(UrlResource.class);
        } catch (URISyntaxException | ClientHandlerException | UniformInterfaceException ex) {
            throw new IllegalStateException("Cannot request " + UrlResource.class.getSimpleName(), ex);
        }
    }

    private URI getUri(String... paths) throws URISyntaxException {
        UriBuilder builder = UriBuilder.fromPath("http://" + host + ":" + port);
        for (String path : paths) {
            builder.path(path);
        }
        return builder.build();
    }
}
